#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: ZhengShiQi
@file: config_manager.py
@time: 2025/8/27 17:06
@desc: 配置管理器
"""

import os
import yaml
from typing import Dict, Any
from pydantic import BaseModel


class BrowserConfig(BaseModel):
    """浏览器配置模型"""
    arguments: list = []
    experimental_options: dict = {}
    page_load_strategy: str = "normal"


class EnvironmentConfig(BaseModel):
    """环境配置模型"""
    timeout: int = 10
    window_size: tuple = None
    headless: bool = False
    local_driver: bool = True


class TestConfig:
    """测试配置管理类，支持多环境测试配置管理"""
    _instance = None
    _initialized = False
    
    def __new__(cls, env_name: str = "local"):
        if cls._instance is None:
            cls._instance = super(TestConfig, cls).__new__(cls)
        return cls._instance
    
    def __init__(self, env_name: str = "local"):
        if TestConfig._initialized:
            return
        
        self.env_name = env_name
        self.config_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "env")
        self._load_config()
        TestConfig._initialized = True
    
    def _load_config(self):
        """加载配置文件"""
        # 加载基础配置
        base_config = self._load_yaml(os.path.join(self.config_dir, "base.yaml"))
        
        # 加载环境特定配置
        env_config_path = os.path.join(self.config_dir, f"{self.env_name}.yaml")
        if os.path.exists(env_config_path):
            env_config = self._load_yaml(env_config_path)
            # 合并配置
            self.config = self._deep_merge(base_config, env_config)
        else:
            self.config = base_config
        
        # 应用运行时覆盖
        self._apply_runtime_overrides()
        
        # 创建配置模型实例
        self.common = EnvironmentConfig(**self.config.get("common", {}))
        self.browsers = {name: BrowserConfig(**config) for name, config in self.config.get("browsers", {}).items()}
    
    def _load_yaml(self, file_path: str) -> Dict[str, Any]:
        """加载YAML配置文件"""
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f) or {}
    
    @property
    def chrome_options(self):
        """获取Chrome浏览器配置"""
        return self.get_browser_config("chrome")
    
    def get_browser_config(self, browser_name: str) -> Dict[str, Any]:
        """根据浏览器名称获取配置"""
        return self.config.get("browsers", {}).get(browser_name, {})
    
    def _deep_merge(self, base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
        """递归深度合并两个字典"""
        result = base.copy()
        for key, value in override.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._deep_merge(result[key], value)
            else:
                result[key] = value
        return result
    
    def _apply_runtime_overrides(self):
        """应用运行环境或命令行动态配置"""
        # 这里可以添加从环境变量或命令行参数获取配置的逻辑
        pass